//
//  DDErandChangeViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-21.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "DDErandChangeViewController.h"
#import "CommonDatePickerViewController.h"
#import "CommonPickerViewController.h"
#import "OtherPickerViewController.h"
#import "SBJson.h"
#import "MTStatusBarOverlay.h"

@interface DDErandChangeViewController () <CommonDatePickerDelegate,CommonPickerDelegate,OtherPickerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *erandReasonLbl;
@property (weak, nonatomic) IBOutlet UITextField *erandPlaceTf;
@property (weak, nonatomic) IBOutlet UILabel *jxsNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *jxsCodeLbl;
@property (weak, nonatomic) IBOutlet UITextField *changeReasonTf;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *erandWayLbl;

@property (nonatomic, strong) CommonPickerViewController *picker;
@property (nonatomic, strong) OtherPickerViewController *otherPicker;
@property (nonatomic, strong) NSMutableArray *ccmdArray; //出差目的
@property (nonatomic, strong) NSString *bgxmmc;//目的其他，事由
@property (nonatomic, strong) NSMutableArray *sellerList;

@end

@implementation DDErandChangeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self querySellerListByAreaType];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"出差变更申请";
    self.showLeftBtn = YES;
    self.showRightBtn = YES;
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    [self updateViewWithErandInfo];
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightNavItemAction:(id)sender {
    NSString *reason = self.erandReasonLbl.text;
    NSString *place = self.erandPlaceTf.text;
    NSString *merchantName = self.jxsNameLbl.text;
    NSString *merchantCode = self.jxsCodeLbl.text;
    NSString *changeReason = self.changeReasonTf.text;
    NSString *erandWay = self.erandWayLbl.text;
    NSString *bgxmmc = self.bgxmmc;
    if ([reason length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差目的不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([place length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差地点不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([erandWay length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差方式不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([merchantName length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"您还没有选择经销商，请选择"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([changeReason length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"变更理由不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        
        NSString *erandID = [self.erandInfo objectForKeyOrNil:@"id"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               erandID,@"id",
                               reason,@"bgmd",
                               place,@"ccdd",
                               erandWay,@"ccfs",
                               merchantName,@"jxsmc",
                               merchantCode,@"jxsdm",
                               changeReason,@"bgly",
                               gonghao,@"gh",
                               bgxmmc,@"bgxmmc",
                               nil];
        [self.networkManager requestWithMethod:updateApply parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

- (void)updateViewWithErandInfo {
    NSMutableDictionary *data = self.erandInfo;
    
    NSString *reason = [data objectForKeyOrNil:@"ccmd"];
    NSString *merchantName = [data objectForKeyOrNil:@"jxsmc"];
    NSString *merchantCode = [data objectForKeyOrNil:@"jxsdm"];
    NSString *erandPlace = [data objectForKeyOrNil:@"ccdd"];
    NSString *erandWay = [data objectForKeyOrNil:@"ccfs"];
   
    self.erandReasonLbl.text = reason;
    self.bgxmmc = reason;
    self.jxsNameLbl.text = merchantName;
    self.jxsCodeLbl.text = merchantCode;
    self.erandPlaceTf.text = erandPlace;
    if ([erandWay length] > 0) {
        self.erandWayLbl.text = erandWay;
    }

}

//根据职位动态获取出差目的
- (NSMutableArray*) getZhiWeiArray:(NSString*)zhiwei {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@=%@%@%@", SERVER_DOMAIN, @"?ctrl_bussinecs", @"getDictService", @"&input_dtype=CCMD&input_dname=", zhiwei];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *recived = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *recivedStr = [[NSString alloc] initWithData:recived encoding:gbkEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSDictionary *resultDict = [parser objectWithString:recivedStr];
    request = nil;
    parser = nil;
    recivedStr = nil;
    NSDictionary *dataDict = [resultDict objectForKey:@"data"];
    dataDict = [dataDict objectForKey:@"dict"];
    NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:3];
    for (NSDictionary *item in dataDict) {
        NSString *dvalue = [item objectForKey:@"dvalue"];
        [mutableArray addObject:dvalue];
    }
    self.ccmdArray = mutableArray;
    return mutableArray;
}


//根据区域表示查询经销商列表
- (void)querySellerListByAreaType {
    UserInfo *user = [UserInfo instance];
    NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
    NSString *type = [user.info objectForKeyOrNil:@"dqbs"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:gonghao,@"gh", nil];
    RequestMethodId method = sellerInfoA;
    if ([type isEqualToString:@"A"]) {
        method = sellerInfoA;
    } else if ([type isEqualToString:@"B"]) {
        method = sellerInfoB;
    }
    [self.networkManager requestWithMethod:method parameter:param delegate:self];
    [self.HUD show:YES];
}

//获取经销商信息后，赋默认值
- (void)setSellerDefaultValue {
    if ([self.sellerList count] > 0) {
        NSDictionary *firstSeller = [self.sellerList objectAtIndex:0];
        NSString *name = [firstSeller objectForKeyOrNil:@"jxsmc"];
        NSString *code = [firstSeller objectForKeyOrNil:@"jxsdm"];
        
        self.jxsNameLbl.text = name;
        self.jxsCodeLbl.text = code;
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == sellerInfoA || methodId == sellerInfoB) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    
                    if ([dataObject isKindOfClass:[NSArray class]]) {
                        self.sellerList = [NSMutableArray arrayWithArray:dataObject];
                        [self setSellerDefaultValue];
                    }
                }
                
                [self.tableView reloadData];
            }
            
        }
    } else if (methodId == updateApply) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    NSInteger resultCode = [[dataObject objectForKey:@"result"] integerValue];
                    if (resultCode == 0) { //提交成功
                        
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差变更申请提交成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;
                        
                        [self showAlertViewWithMessage:@"出差变更申请提交成功"];
                        
                        [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                        
                    } else if (resultCode == 1) {
                        NSString *msg = @"该人员没有对应的临店项目，请联系管理员";
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:msg
                                                                       delegate:nil
                                                              cancelButtonTitle:@"确定"
                                                              otherButtonTitles:nil];
                        [alert show];
                    }
                }
            }
        }
        
    }
    
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    if ([msg length] == 0) {
        msg = @"请求失败，请稍后重试";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.inputAccessoryView == nil) {
        UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        [topView setBarStyle:UIBarStyleDefault];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(320-42, 3, 40, 26);
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [button addTarget:self action:@selector(dismissKeyBoard:) forControlEvents:UIControlEventTouchUpInside];
        
        [topView addSubview:button];
        
        [textField setInputAccessoryView:topView];
    }
    return YES;
}

- (void)dismissKeyBoard:(id)sender {
    [self.view endEditing:YES];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    switch (row) {
        case 0: { //出差目的
            self.otherPicker = (OtherPickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"OtherPicker"];
            _otherPicker.delegate = self;
            if(self.ccmdArray == nil){
                UserInfo *user = [UserInfo instance];
                [self getZhiWeiArray:[user.info objectForKey:@"zw"]];
            }
            //            NSArray *componentData = [NSArray arrayWithObjects:@"临店",@"驻店",@"其他" ,nil];
            _otherPicker.datas = [NSArray arrayWithObjects:self.ccmdArray, nil];
            _otherPicker.view.tag = 20001;
            _otherPicker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
            AppDelegate *app = [AppDelegate sharedDelegate];
            [app.window addSubview:_otherPicker.view];
            
            break;
        }
        case 2: { //出差方式
            self.picker = (CommonPickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonPicker"];
            _picker.delegate = self;
            NSArray *componentData = [NSArray arrayWithObjects:@"飞机",@"其他" ,nil];
            _picker.datas = [NSArray arrayWithObjects:componentData, nil];
            _picker.view.tag = 20002;
            _picker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
            AppDelegate *app = [AppDelegate sharedDelegate];
            [app.window addSubview:_picker.view];
            break;
        }
        case 3: { //经销商名称
            self.picker = (CommonPickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonPicker"];
            _picker.delegate = self;
            NSMutableArray *sellerNames = [NSMutableArray array];
            if ([self.sellerList count] > 0) {
                for (NSDictionary *seller in self.sellerList) {
                    NSString *name = [seller objectForKeyOrNil:@"jxsmc"];
                    if (name != nil) {
                        [sellerNames addObject:name];
                    }
                }
            }
            _picker.datas = [NSArray arrayWithObjects:sellerNames, nil];
            _picker.view.tag = 20003;
            _picker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
            AppDelegate *app = [AppDelegate sharedDelegate];
            [app.window addSubview:_picker.view];
            break;
        }
        case 4: { //经销商代码

            break;
        }
        default:
            break;
    }
}

#pragma mark - CommonPickerDelegate
- (void)picker:(CommonPickerViewController *)picker didSelectedItemIndexSet:(NSDictionary *)selectedItems {
    NSInteger index = [[selectedItems objectForKey:[NSNumber numberWithInt:0]] integerValue];
    
    NSInteger tag = picker.view.tag;
    if (tag == 20001) { //出差目的
        if(self.ccmdArray == nil){
            UserInfo *user = [UserInfo instance];
            [self getZhiWeiArray:[user.info objectForKey:@"zw"]];
        }
        NSArray *tiles = [NSArray arrayWithObjects:self.ccmdArray ,nil];
        NSString *other = [[tiles objectAtIndex:0] objectAtIndex:index];
        if([other isEqualToString:@"其他"]){
            NSString *otherText = [self.otherPicker getOther];
            self.erandReasonLbl.text = other;
            self.bgxmmc = otherText;
        }else{
            self.erandReasonLbl.text = other;
        }
    } else if (tag == 20002) { //出差方式
        NSArray *tiles = [NSArray arrayWithObjects:@"飞机",@"其他" ,nil];
        self.erandWayLbl.text = [tiles objectAtIndex:index];
    } else if (tag == 20003) { //经销商名称/代码
        if ([self.sellerList count] > index) {
            NSDictionary *seller = [self.sellerList objectAtIndex:index];
            NSString *name = [seller objectForKeyOrNil:@"jxsmc"];
            NSString *code = [seller objectForKeyOrNil:@"jxsdm"];
            self.jxsNameLbl.text = name;
            self.jxsCodeLbl.text = code;
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
